package com.serialcommunication.helper;

import java.util.BitSet;

import org.apache.soap.encoding.Hex;

import com.serialcommunication.constants.ProtocolConstants;

public class ByteUtil {

	

	public static byte hexToByte(Hex hexString) {
		return hexString.getBytes()[0];
	}

	/**
	 * Change largest bit of byte to 1
	 * 
	 * @param b
	 * @return
	 */
	public static byte modifyLargestBit(byte b) {
		BitSet bitSet = getBitsFromByte(b);
		Hex hex = bytesToHex(bitSet.toByteArray());
		return hex.getBytes()[0];
	}

	public static Hex bytesToHex(byte[] bytes) {
		final char[] hexArray = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
				'9', 'A', 'B', 'C', 'D', 'E', 'F' };
		char[] hexChars = new char[bytes.length * 2];
		int v;
		for (int j = 0; j < bytes.length; j++) {
			v = bytes[j] & 0xFF;
			hexChars[j * 2] = hexArray[v >>> 4];
			hexChars[j * 2 + 1] = hexArray[v & 0x0F];
		}
		return new Hex(new String(hexChars));
	}

	public static BitSet getBitsFromByte(byte b) {
		BitSet bits = new BitSet(8);
		for (int i = 0; i < 8; i++) {
			if (i == 7) {
				bits.set(i, true);
			} else {
				bits.set(i, (b & 1) == 1);
				b >>= 1;
			}
		}
		return bits;
	}
	
	public static byte[] setSigleBitOfPayloadBytes(int bitNumber) {
		BitSet bits = new BitSet(ProtocolConstants.NUMBER_OF_PAYLOAD_BYTES - 1);
		bits.set(bitNumber - 1);
		byte[] retValue = bits.toByteArray();
		return retValue;
	}
}
